import os
import json

DATA_FILE = "data/messages.json"

def load_all_messages_from_file():
    if not os.path.exists(DATA_FILE):
        return []
    with open(DATA_FILE, "r", encoding="utf-8") as f:
        try:
            return json.load(f)
        except json.JSONDecodeError:
            return []

def save_message_to_file(message):
    all_messages = load_all_messages_from_file()
    all_messages.append(message)
    with open(DATA_FILE, "w", encoding="utf-8") as f:
        json.dump(all_messages, f, ensure_ascii=False, indent=4)

def delete_message_by_id(message_id):
    all_messages = load_all_messages_from_file()
    new_messages = [msg for msg in all_messages if msg["message_id"] != message_id]
    with open(DATA_FILE, "w", encoding="utf-8") as f:
        json.dump(new_messages, f, ensure_ascii=False, indent=4)

def update_message_by_id(message_id, new_content):
    all_messages = load_all_messages_from_file()
    for msg in all_messages:
        if msg["message_id"] == message_id:
            msg["content"] = new_content
            break
    with open(DATA_FILE, "w", encoding="utf-8") as f:
        json.dump(all_messages, f, ensure_ascii=False, indent=4)

def add_comment_to_message(message_id, comment):
    all_messages = load_all_messages_from_file()
    for msg in all_messages:
        if msg["message_id"] == message_id:
            if "comments" not in msg:
                msg["comments"] = []
            msg["comments"].append(comment)
            break
    with open(DATA_FILE, "w", encoding="utf-8") as f:
        json.dump(all_messages, f, ensure_ascii=False, indent=4)

def like_message(message_id):
    all_messages = load_all_messages_from_file()
    for msg in all_messages:
        if msg["message_id"] == message_id:
            if "likes" not in msg:
                msg["likes"] = 0
            msg["likes"] += 1
            break
    with open(DATA_FILE, "w", encoding="utf-8") as f:
        json.dump(all_messages, f, ensure_ascii=False, indent=4)